<template>
  <div class="padding-16">
    <a-card class="general-card" title="部门管理">
      <a-form
        ref="refSearchForm"
        :model="searchForm"
        auto-label-width
      >
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="name" label="部门名称">
              <a-input v-model="searchForm.name" placeholder="请输入部门名称"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="status" label="状态">
              <a-select v-model="searchForm.status" :options="statusOptions" placeholder="全部"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-space :size="16">
              <a-button type="primary" @click="fetchTableData()">
                <template #icon>
                  <icon-search/>
                </template>
                查询
              </a-button>
              <a-button @click="$refs.refSearchForm.resetFields()">
                <template #icon>
                  <icon-refresh/>
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-divider style="margin-top: 0"/>
      <a-space style="margin-bottom: 16px">
        <a-button size="small" type="primary" @click="handleEdit({}, 'add')">
          <template #icon>
            <icon-plus/>
          </template>
          新增
        </a-button>
        <a-button size="small" @click="handleExpandAll()">展开/折叠</a-button>
      </a-space>
      <a-table
        ref="refTable"
        bordered
        row-key="id"
        default-expand-all-rows
        :data="tableData"
        :loading="pageLoading"
        :pagination="false"
      >
        <template #columns>
          <a-table-column title="部门名称" data-index="name"></a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <DictBadge :options="statusOptions" :value="record.status"/>
            </template>
          </a-table-column>
          <a-table-column title="排序" data-index="sort"></a-table-column>
          <a-table-column title="备注" data-index="remark"></a-table-column>
          <a-table-column title="更新时间" data-index="update_time"></a-table-column>
          <a-table-column title="操作" :width="230">
            <template #cell="{ record }">
              <a-button type="text" @click="handleEdit(record, 'edit')">编辑</a-button>
              <a-button type="text" @click="handleEdit(record, 'add')">新增</a-button>
              <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                <a-button v-if="record.id !== 10000" type="text" status="danger">删除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增 & 编辑 弹窗 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="`${formState.id ? '编辑' : '创建'}部门`"
      width="680px"
      :footer="false">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        auto-label-width
        @submit="handleSubmit"
      >
        <a-form-item label="上级部门" field="pid">
          <a-tree-select
            v-model="formState.pid"
            :data="departOptions"
            :field-names="fieldNames"
            placeholder="请选择上级部门"
          ></a-tree-select>
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="部门名称" field="name">
              <a-input v-model="formState.name" placeholder="请输入部门名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序" field="sort">
              <a-input-number v-model="formState.sort" :min="1" :max="9999"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="负责人" field="leader">
              <a-input v-model="formState.leader" placeholder="部门负责人" :maxlength="20"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" field="mobile">
              <a-input v-model="formState.mobile" placeholder="负责人联系电话" :maxlength="20"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" field="status">
              <a-radio-group v-model="formState.status">
                <a-radio :value="1">正常</a-radio>
                <a-radio :value="2">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formState.remark"
            placeholder="简介"
            auto-size
            :maxlength="200"
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <div class="form-footer">
          <a-button key="submit" html-type="submit" type="primary" :loading="pageLoading">确 定</a-button>
          <a-button class="ml-24" @click="handleCancel">取 消</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";
import DeptAPI from "@/api/system/dept";
import {statusOptions} from "@/enums/status";

export default defineComponent({
  data() {
    return {
      pageLoading: false,
      statusOptions,
      isExpandAll: false,
      tableData: [],
      // 搜索表单
      searchForm: {
        name: "",
        status: ""
      },
      // 部门树选择
      departOptions: [],
      fieldNames: {
        title: "name",
        key: "id",
        children: "children"
      },
      // 创建弹窗
      dialogVisible: false,
      formState: {
        id: undefined,
        name: undefined,
        pid: 0,
        remark: undefined,
        status: 1,
        sort: 1,
        leader: undefined,
        mobile: undefined,
      },
      formRules: {
        pid: [{required: true, message: "上级部门不能为空", trigger: "change"}],
        name: [{required: true, min: 2, message: "至少2个字符", trigger: "change"}],
        sort: [{required: true, message: "排序不能为空", trigger: "blur"}],
        status: [{required: true, message: "状态不能为空", trigger: "blur"}],
        // mobile: [{required: false, message: "排序不能为空", trigger: "blur"}],
      }
    };
  },
  mounted() {
    this.fetchTableData();
  },
  methods: {
    handleExpandAll() {
      this.isExpandAll = !this.isExpandAll
      this.$refs.refTable.expandAll(this.isExpandAll)
    },
    async fetchTableData(extraParam = {}) {
      this.pageLoading = true;
      try {
        let params = {
          ...this.searchForm
        };
        if (extraParam) {
          params = {
            ...params,
            ...extraParam
          };
        }
        const {data} = await DeptAPI.getList(params);
        this.tableData = data || [];
        if (!this.searchForm.name && this.searchForm.status === '') {
          this.departOptions = data || []
        }
      } catch (err) {
        console.warn(err);
        // Message.error("出了点小问题，请稍后重试！");
      }
      this.pageLoading = false;
    },
    // 操作
    async handleDelete(rowData) {
      if (!rowData.id) return;
      this.pageLoading = true;
      try {
        const {msg} = await DeptAPI.del(rowData);
        this.$message.success(msg || "删除成功！");
        await this.fetchTableData();
      } catch (err) {
        // you can report use errorHandler or other
      } finally {
        this.pageLoading = false;
      }
    },
    // 创建表单
    handleEdit(rowData: any, type = "add") {
      this.dialogVisible = true;
      if (rowData.id && type === "edit") {
        this.formState = {
          id: rowData.id,
          name: rowData.name,
          pid: rowData.pid,
          remark: rowData.remark,
          status: rowData.status,
          sort: rowData.sort,
          leader: rowData.leader,
          mobile: rowData.mobile,
        };
      } else {
        this.formState.pid = rowData.id || 0;
      }
    },
    handleCancel() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.dialogVisible = false;
    },
    async handleSubmit({values, errors}) {
      // console.log("values:", values, "\nerrors:", errors);
      if (!errors) {
        const params = {
          ...this.formState
        };

        this.pageLoading = true;
        try {

          if (params.id) {
            await DeptAPI.update(params);
          } else {
            await DeptAPI.create(params);
          }

          this.$message.success("保存成功！");
          await this.fetchTableData();
          this.handleCancel();
        } catch (err) {
          // you can report use errorHandler or other
        } finally {
          this.pageLoading = false;
        }
      }
    }
  }
});
</script>


<style scoped lang="less">
.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
